<template>
	<view class="manyCar-page" :style="{'padding-top': navHeight}">
		<navbar navType="text" 
			:cText="cText" 
			rText="分组" :isBtn="true" 
			@onRightSumbit="onRightSumbit">
		</navbar>

		<map id="map" class="map" :scale="scale" :longitude="longitude" :latitude="latitude"
			:include-points="markers"
			:show-location="showLocation" :enable-traffic="isTraffic" :enable-satellite="isSatellite" :markers="markers"
			@markertap="markertap">
			<top-window :isTraffic="isTraffic" :type="'manyCar'" :satellite="isSatellite" :joinCluster="joinCluster"
				:text="noticeText" @onTopMethods="onTopMethods"></top-window>
			<!-- 抽屉触发按钮 -->
			<image :src="carOpenUrl" mode="aspectFit" class="fixed-left" @tap="handleDrawer"></image>
			<!-- 上一辆 下一辆 选择-->
			<tar @onTarClick="onTarClick"></tar>
			<!-- 抽屉 -->
			<uni-drawer ref="showLeft" mode="left" :width="220">
				<scroll-view :style="{'padding-top': navHeight}" scroll-y="true" class="drawer-view">
					<template v-for="item in markers" >
						<view v-if="filterOperatorName(item.title)" :key="item.id" class="item" @click="handleThis(item.id)">
							<image :src="item.iconPath" mode="aspectFill"></image>
							<text>{{item.title}}</text>
						</view>
					</template>
					
					<view class="" style="height: 220rpx;">
						
					</view>
				</scroll-view>
				<view class="filterWrapper" >
					<u-search placeholder="请输入姓名" :value="keyword" @blur="onSearch" @clear="onClear" @search="onSearch"></u-search>
				</view>
				
			</uni-drawer>
			<!-- 抽屉 -->
			<!-- 刷新时间 S -->
			<u-popup :show="showCenter" :round="10" :safe-area-inset-bottom="false" mode="center"
				@close="showCenter = false">
				<popup title="刷新时间" :lists="popLists" :popInputShow="true" @onSumbit="onBtnClick"></popup>
			</u-popup>
			<!-- 刷新时间 E -->
			<!-- <car-icon ref="carIconRef" :triangle="false" :height="navHeight"></car-icon> -->
		</map>

		<view class="custom" :style="{height: customHeight + 'rpx'}">
			<custom :customObj="customObj" :customHeight="600" @onCustomMethods="onCustomMethods"></custom>
		</view>

	</view>
</template>

<script>
	import constant from '@/utils/constant'
	import {
		mapState,
		mapMutations,
		mapActions
	} from 'vuex';
	import navbar from '@/components/navbar/index.vue';
	import popup from '@/components/popup/index.vue';
	import carIcon from '@/components/carIcon/index.vue'

	import topWindow from '../components/mapComponents/topWindow1.vue';
	import tar from '../components/mapComponents/tar.vue';
	import custom from '../components/mapComponents/custom.vue';
	import utils from '@/utils/utils';
	import hwOperatorLocationApi from '@/api/hwOperator/hwOperatorLocationApi'
	let that = null
	export default {
		components: {
			navbar,
			topWindow,
			tar,
			custom,
			popup,
			carIcon
		},
		data() {
			return {
				noticeText: "",
				//  manyCar: '多车监控' area: '区域统计'
				carId: '',
				navHeight: '',
				scale: 5,
				longitude: 114.319642,
				latitude: 30.576468,
				markers: [],
				lists: [],
				operatorTotal: 0,
				customHeight: 0,
				customObj: {},
				currentIndex: 0,
				carOpenUrl: this.$appImageUrl + "/xcx/ic_map_open.png",
				showLocation: false,
				showCenter: false,
				isTraffic: false,
				isSatellite: false,
				joinCluster: true,
				popInputShow: false,
				time: 60000,
				timer: null,
				popLists: [{
						name: '10秒',
						value: 10000
					},
					{
						name: '20秒',
						value: 20000
					},
					{
						name: '30秒',
						value: 30000
					},
					{
						name: '40秒',
						value: 40000
					},
					{
						name: '50秒',
						value: 50000
					},
					{
						isInput: true
					}
				],
				keyword:""
			}
		},
		computed: {
			...mapState({
				teamInfo: state => state.operator.operatorTeamInfo,
				operatorInfo: state => state.operator.operatorInfo
			}),
			cText() {
				return `${this.teamInfo.teamName}(${this.operatorTotal})`
			},
		},
		watch: {
			teamInfo(val) {
				console.log("teamInfo:", val)
				clearInterval(this.timer)
				this.scale = this.scale == 5 ? 4 : 5
				this.getData()
			},
			operatorInfo(val){
				if (this.operatorInfo&&this.operatorInfo.id){
					this.customData(this.operatorInfo.id)
				}
			}
		},
		onLoad(options) {
			that = this
		},
		onReady() {
			this._mapContext = uni.createMapContext("map", this);
			this._mapContext.initMarkerCluster({
				enableDefaultStyle: true,
				zoomOnClick: true,
				gridSize: 20,
				fail(err) {
					console.log(err)
				},
				complete(res) {
					console.log('initMarkerCluster', res)
				}
			});
			this._mapContext.on("markerClusterCreate", (e) => {
				console.log("markerClusterCreate", e);
			});
			this.getData()
			this.timer = setInterval(() => {
				this.getData()
			}, this.time)
		},
		beforeDestroy() {
			this.$store.commit('SET_OPERATOR_TEAM_INFO', {
				teamName: '全部人员',
				teamId: ''
			})
			this.$store.commit('SET_OPERATOR_INFO', {})
			clearInterval(this.timer)
		},
		methods: {
			onRightSumbit() {
				uni.navigateTo({
					url: '/pages/operator/teamSelect/index'
				})
			},
			handleDrawer() {
				this.$refs.showLeft.open();
			},
			handleThis(id) {
				this.$refs.showLeft.close();
				this.customData(id)
			},
			onBtnClick(act, time) {
				var count = 0
				if (this.act == 5) {
					count = time
				} else {
					count = this.popLists[act].value
				}
				if (count> 10000){
					this.time = count
					clearInterval(this.timer)
					this.timer = setInterval(() => {
						this.getData()
					}, this.time)
				}
			},
			onTopMethods(str) {
				if (str === 'traffic') {
					this.isTraffic = !this.isTraffic
				} else if (str === 'satellite') {
					this.isSatellite = !this.isSatellite
				} else if (str === 'all') {
					this.getData()
				} else if (str === 'clear') {
					this._mapContext.addMarkers({
						markers: [],
						clear: true,
						complete(res) {
							console.log('addMarkers', res)
						}
					})
				} else if (str === 'time') {
					this.showCenter = true
				} else if (str === 'together') {
					this.getData(!this.joinCluster)
				}
			},
			onCustomMethods(str) {
				if (str === 'freshen') {
					this.getData()
				} else if (str === 'close') {
					this.customHeight = 0
				}
			},
			onTarClick(str) {
				if (str === 'local') {
					uni.getLocation({
						type: 'gcj02',
						success: (res) => {
							this.scale = this.scale == 15 ? 16 : 15
							this.latitude = res.latitude
							this.longitude = res.longitude
							this.showLocation = true
						},
						fail: () => {
							uni.getSetting({
								success(res) {
									if (!res.authSetting['scope.userLocation']) {
										uni.openSetting({
											success(data) {
												console.log(data)
											},
											fail(error) {
												console.log(error)
											}
										})
									}
								}
							})
						}
					});
				} else if (str === 'prev') {
					if (this.currentIndex == 0) {
						this.currentIndex = this.lists.length - 1
					} else {
						this.currentIndex--
					}
					this.customData()
				} else if (str === 'next') {
					if (this.currentIndex == this.lists.length - 1) {
						this.currentIndex = 0
					} else {
						this.currentIndex++
					}
					this.customData()
				} else if (str === 'current') {
					this.customData()
				} else  {
					// this.$refs.carIconRef.getData()
				}
			},
			markertap(e) {
				const {
					markerId
				} = e.detail;
				this.customData(markerId)
			},
			customData(id) {
				if (id) {
					this.currentIndex = this.lists.findIndex(item => item.id == id)
					this.id = id
				} else {
					this.id = this.lists[this.currentIndex].id
				}
				const item = this.lists[this.currentIndex]
				this.longitude = item.lng
				this.latitude = item.lat
				this.scale = this.scale == 15 ? 16 : 15
				this.customObj = {
					id: item.id,
					operatorName: item.operatorName,
					jobNum: item.jobNum,
					workType: item.workType,
					onlineStatus: item.onlineStatus=='1'?'在线':'离线',
					gnssCount: item.gnssCount,
					signalStrength: item.signalStrength,
					directionName: item.directionName,
					direction: item.direction,
					phone: item.phone,
					satl: item.satl,
					sgn: item.sgn,
					drctCn: item.drctCn,
					speed: `${item.speed||'0.00'}km/h`,
					runStopTime: item.runStopTime,
					mileage: `${item.mileage||'0.00'}km`,
					mileageTotal: `${item.mileageTotal||'0.00'}km`,
					time: item.time,
					teamName: item.teamName,
					drvName: item.drvName,
					drvPhone: item.drvPhone,
					plateColor: item.plateColor,
					addr: item.addr,
					latitude: item.lat,
					longitude: item.lng
				}
				this.$store.commit('SET_OPERATOR_INFO',item)

				this.customHeight = 600
			},
			getData(isClose = true) {
				uni.showLoading({
					title: '获取数据中',
					mask: true
				})


				// 清空点聚合---防止地图重复标记
				if (this.markers.length > 0) {
					const ids = this.markers.reduce((prev, cur) => {
						return [...prev, cur.id]
					}, [])
					this._mapContext.removeMarkers({
						markerIds: ids
					})
				}

				hwOperatorLocationApi.hwOperatorRealTime({
					
				}).then((res) => {
					if (res.code == 200) {
						var list = res.data.operatorList
						const result = []
						var dataList = []
						var total = 0;
						var online = 0;
						var offline = 0;

						for (var i in list) {
							var item = list[i]
							if (!(item.teamId&&item.teamId.length>0)){
								item.teamId = "other"
							}
							item.directionName = utils.directionToString(item.direction)
							if (that.teamInfo.teamId==''||item.teamId == that.teamInfo.teamId){
								if ((-90<item.lat)&&(item.lat<90)&&(-180<item.lng)&&(item.lng<180)){
									const itemJson = {
										id: item.id * 1, //(item.id * 1)%1000000000,
										latitude: item.lat * 1,
										longitude: item.lng * 1,
										title: item.operatorName,
										label: item.operatorName,
										width: 30,
										height: 30,
										iconPath: item.positionImg || constant.defaultMapIcon,
										joinCluster: isClose
									}
									result.push(itemJson)
								}
								
								dataList.push(item)
								if (item.onlineStatus == '1'){
									online++
								}else{
									offline++
								}
								total++;				
							}
						}
						this.noticeText = `全部人员: ${total}, 在线人员: ${online}, 离线人员: ${offline}`
						console.log("result", result)
						uni.hideLoading()
						this.markers = result
						this.lists = dataList
						this.operatorTotal = total
						this.joinCluster = isClose

						this._mapContext.addMarkers({
							markers: result,
							clear: true,
							complete(res) {
								console.log('addMarkers', res)
							}
						})
					}
				})
			},
			filterOperatorName(name){
				return name.toLowerCase().includes(this.keyword.toLowerCase())
			},
			onSearch(val){
				this.keyword = val
			},
			onClear(){
				this.keyword = ""
			}
		}
	}
</script>

<style scoped>
	.manyCar-page {
		height: 100vh;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
	}

	.map {
		width: 750rpx;
		flex: 1;
	}

	.fixed-left {
		width: 54rpx;
		height: 98rpx;
		position: fixed;
		left: -2rpx;
		top: 50%;
		transform: translateY(-50%);
	}

	.drawer-view {
		height: 100%;
		box-sizing: border-box;
	}

	.item {
		display: flex;
		align-items: center;
		padding: 15rpx 10rpx;
		font-size: 28rpx;
	}

	.item:first-child {
		padding-top: 30rpx;
	}

	.item image {
		width: 40rpx;
		height: 40rpx;
		margin-right: 20rpx;
	}

	.custom {
		overflow: hidden;
		background: #fff;
		transition: height 0.3s ease;
		box-sizing: border-box;
	}
	
	.filterWrapper{
		position: absolute;
		bottom: 0;
		left: 0;
		width: 220px;
		padding: 20rpx 10rpx 60rpx 10rpx;
		background-color: #fff;
		box-sizing: border-box;
		border-top: 1px solid #f3f3f3;
	}
</style>